import BaseAxiosRequest,{ errorHandler } from '@ohos/BaseLibrary/src/main/ets/http/BaseAxiosRequest';
import { loadingEventBus } from '@ohos/BaseLibrary/src/main/ets/utils/EventBus';
import NetworkStatusUtil from '@ohos/BaseLibrary/src/main/ets/utils/NetworkStatusUtil';
import { AxiosRequestHeaders } from '@ohos/axios';
import { promptAction } from '@kit.ArkUI';
import { connection } from '@kit.NetworkKit';

/**
 * @ProjectName : MyApplication
 * @FileName : axiosClient
 * @Author : 小北哥
 * @Time : 2024/8/1
 *
 * axios请求客户端创建
 */
const AxiosRequest = new BaseAxiosRequest({
  timeout: 10 * 1000,
  checkResultCode: false,
  headers: {
    'Content-Type': 'application/json'
  } as AxiosRequestHeaders,
  interceptorHooks: {
    requestInterceptor: async (config) => {
      // try {
      //   await NetworkStatusUtil.checkNetworkStatus();
      // } catch (error) {
      //   console.log('AxiosRequest: 网络未连接');
      //   loadingEventBus.emit('noNetwork', 'loading');
      //   return Promise.reject(new Error('网络未连接'));
      // }
      // if (!connection.hasDefaultNet()) {
      //   console.log('AxiosRequest: 网络未连接');
      //   loadingEventBus.emit('noNetwork', 'loading');
      //   return Promise.reject(new Error('网络未连接'));
      // }

      console.log(`AxiosRequest 请求方法: ${config.method}\n` + `AxiosRequest 请求链接: ${config.url}\n`
        + `AxiosRequest Params: ${JSON.stringify(config.params)}\n` +  `AxiosRequest data: ${JSON.stringify(config.data)}`);

      AxiosRequest.config.showLoading = config.showLoading
      if (config.showLoading) {
        console.log(`AxiosRequest 加载中...`)
        loadingEventBus.emit('showLoading', 'loading');

        // 引入延迟（例如 2 秒）
        setTimeout(() => {
          loadingEventBus.emit('showLoading', 'loading');
        }, 5000);
      }
      if (config.checkLoginState) {
        console.log(`AxiosRequest 登录状态校验>>>: `)
        // 思路登录后个人信息本地示例化，先获取个人信息如 UserInfo 将用户的ID初始化为-1
        // if (UserInfo.id === -1) {
        //    router.pushUrl({ url: 'pages/login'}) // 跳转到登录
        // }
      }
      return config;
    },
    requestInterceptorCatch: (err) => {
      console.log(`AxiosRequest RequestError: ` + err.toString())
      if (AxiosRequest.config.showLoading) {
        loadingEventBus.emit('hideLoading', 'loading');
      }
      return err;
    },
    responseInterceptor: (response) => {
      if (AxiosRequest.config.showLoading) {
        loadingEventBus.emit('hideLoading', 'loading');
      }
      console.log(`AxiosRequest 响应Response: ` + JSON.stringify(response.data))
      if (response.status === 200) {
        // 所以在实现的子类我设置成非必传会报错，加了个忽略注解
        // @ts-ignore
        const checkResultCode = response.config.checkResultCode
        if (checkResultCode && response.data.errorCode != 0) {
          promptAction.showToast({ message: response.data.errorMsg});
          return Promise.reject(response)
        }

        if (response.data.code === 2000) {
          const data = response.data.data;
          if (data === undefined || data === null ||
            (typeof data === 'object' && Object.keys(data).length === 0) ||
            (Array.isArray(data) && data.length === 0)) {
            loadingEventBus.emit('noData', 'loading');
          } else {
            return Promise.resolve(response.data);
          }
        } else {
          errorHandler(response);
        }
      } else {
        return Promise.reject(response);
      }
    },
    responseInterceptorCatch: (error) => {
      if (AxiosRequest.config.showLoading) {
        console.log(`AxiosRequest 错误信息 关闭加载...`)
        loadingEventBus.emit('hideLoading', 'loading');
      }
      console.log(`AxiosRequest 网络请求响应异常: ` + error.toString())
      errorHandler(error);
      return Promise.reject(error);
    },
  }
});

export default AxiosRequest;